package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;

import cn.edu.sdjzu.xg23.kcsj01_backend.entity.EmployeeAssReward;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Reward;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.*;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.RewardService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class RewardServiceImpl implements RewardService {

    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Autowired
    private RewardMapper rewardMapper;
    @Autowired
    private AbsAchievementMapper absAchievementMapper;
    @Autowired
    private EmployeeAssRewardMapper employeeAssRewardMapper;
    @Override
    @Transactional // 声明事务
    public boolean save(Reward reward) {
        Long sharedId = idGenerator.generateId();

        // 1. 插入 Achievement 相关记录
        absAchievementMapper.addAchievement(sharedId, "奖励");

        // 2. 插入 Reward 记录
        reward.setId(sharedId);
        boolean success = rewardMapper.insert(reward);
        boolean insertSuccess = false;
        if (success && reward.getApplicants() != null && !reward.getApplicants().isEmpty()) {
            for (EmployeeAssReward applicant : reward.getApplicants()) {
                applicant.setReward(new Reward(sharedId));// 设置关联
            }

            insertSuccess  = employeeAssRewardMapper.insertApplicants(reward.getApplicants());
        }
        return success&&insertSuccess;
    }

    @Override
    public  boolean deleteById(Long id) {
        return absAchievementMapper.deleteById(id);
    }

    @Override
    public void update(Reward reward) {
        rewardMapper.update(reward);
    }


    @Override
    public PageInfo<Reward> selectRewardsByCondition(Integer pageNum, Integer pageSize, Reward reward, Long employeeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Reward> rewardList = rewardMapper.selectRewardsByCondition(reward,employeeId);
        return new PageInfo<>(rewardList);
    }
    @Override
    public boolean approveReward(Reward reward) {
        return rewardMapper.approveReward(reward);
    }
}